package com.zxl.live.screen.call.tools;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.session.MediaController;
import android.media.session.MediaSessionManager;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.view.KeyEvent;

import com.zxl.live.screen.call.ui.service.NotifyAccessibilityForJBMR2;
import com.zxl.live.tools.common.ApplicationHelper;

import java.io.IOException;
import java.util.Iterator;

public class CallUtils {

    private static final String MANUFACTURER_HTC = "HTC";

    public static void acceptCall() {
        try {
            if (Build.VERSION.SDK_INT >= 21) {
                answerCallAbove21();
            } else if (Build.VERSION.SDK_INT >= 19) {
                answerCallAbove19();
            } else {
                Runtime.getRuntime().exec("input keyevent " + Integer.toString(KeyEvent.KEYCODE_HEADSETHOOK));
            }
        } catch (Throwable e) {
            e.printStackTrace();
            tryAnswer();
        }
    }

    /**
     * 21+ 且有通知栏读取权限的情况下，可以使用 MediaSessionManager 来模拟媒体事件
     */
    public static boolean hasMediaSessionPermission() {
        return Utils.isNotifyPermissionEnable() && Build.VERSION_CODES.LOLLIPOP <= Build.VERSION.SDK_INT;
    }


    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private static void answerCallAbove21() {
        MediaSessionManager mediaSessionManager = (MediaSessionManager) ApplicationHelper.getContext().getSystemService(Context.MEDIA_SESSION_SERVICE);
        try {
            ComponentName componentName = new ComponentName(ApplicationHelper.getContext(), NotifyAccessibilityForJBMR2.class);
            Iterator<MediaController> iterator = mediaSessionManager.getActiveSessions(componentName).iterator();
            MediaController mediaController = null;
            KeyEvent keyEvent;
            while (iterator.hasNext()) {
                mediaController = iterator.next();
                if ("com.android.server.telecom".equals(mediaController.getPackageName())) {
                    keyEvent = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_HEADSETHOOK);
                    mediaController.dispatchMediaButtonEvent(keyEvent);
                }
            }
        } catch (SecurityException localSecurityException) {
            answerCallAbove19();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private static void answerCallAbove19() {
        AudioManager am = (AudioManager) ApplicationHelper.getContext().getSystemService(Context.AUDIO_SERVICE);
        KeyEvent var6 = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_HEADSETHOOK);
        KeyEvent var7 = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_HEADSETHOOK);
        am.dispatchMediaKeyEvent(var6);
        am.dispatchMediaKeyEvent(var7);
    }


    private static void tryAnswer() {
        try {
            TelephoneHelper.answerCall();
            return;
        } catch (Exception e) {
            e.printStackTrace();
        }
        AudioManager audioManager = (AudioManager) ApplicationHelper.getContext().getSystemService(Context.AUDIO_SERVICE);
        boolean broadcastConnected = MANUFACTURER_HTC.equalsIgnoreCase(Build.MANUFACTURER) && !audioManager.isWiredHeadsetOn();
        if (broadcastConnected) {
            broadcastHeadsetConnected(false);
        }
        try {
            Runtime.getRuntime().exec("input keyevent " + Integer.toString(KeyEvent.KEYCODE_HEADSETHOOK));
        } catch (IOException localIOException1) {
            Intent intentDown = new Intent(Intent.ACTION_MEDIA_BUTTON);
            KeyEvent keyEventDown = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_HEADSETHOOK);
            intentDown.putExtra(Intent.EXTRA_KEY_EVENT, keyEventDown);
            ApplicationHelper.getContext().sendOrderedBroadcast(intentDown, "android.permission.CALL_PRIVILEGED");

            Intent intentUp = new Intent(Intent.ACTION_MEDIA_BUTTON);
            KeyEvent keyEventUp = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_HEADSETHOOK);
            intentUp.putExtra(Intent.EXTRA_KEY_EVENT, keyEventUp);
            ApplicationHelper.getContext().sendOrderedBroadcast(intentUp, "android.permission.CALL_PRIVILEGED");
        } finally {
            if (broadcastConnected) {
                broadcastHeadsetConnected(false);
            }
        }
    }

    private static void broadcastHeadsetConnected(boolean connected) {
        Intent i = new Intent(Intent.ACTION_HEADSET_PLUG);
        i.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
        i.putExtra("state", connected ? 1 : 0);
        i.putExtra("name", "mysms");
        try {
            ApplicationHelper.getContext().sendOrderedBroadcast(i, null);
        } catch (Exception e) {
        }
    }

}
